package day20210630;

import treenode.SimpleTreeNode;

import java.util.LinkedList;
import java.util.Queue;


/**
 * 剑指 Offer 37. 序列化二叉树
 *
 * @author lizy
 * @date 2021/06/30
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        SimpleTreeNode simpleTreeNode = new SimpleTreeNode();
        simpleTreeNode.val = 6;
        simpleTreeNode.right = new SimpleTreeNode(8);
        simpleTreeNode.right.right = new SimpleTreeNode(9);
        simpleTreeNode.right.left = new SimpleTreeNode(7);
        simpleTreeNode.left = new SimpleTreeNode(2);
        simpleTreeNode.left.left = new SimpleTreeNode(2);
        System.out.println(solution.serialize(simpleTreeNode));
        System.out.println("=================================");
        System.out.println(solution.deserialize(solution.serialize(simpleTreeNode)));
    }

    private String serialize(final SimpleTreeNode root) {
        if(root == null) {
            return "[]";
        }
        StringBuilder res = new StringBuilder("[");
        Queue<SimpleTreeNode> queue = new LinkedList<SimpleTreeNode>() {{ add(root); }};
        while(!queue.isEmpty()) {
            SimpleTreeNode node = queue.poll();
            if(node != null) {
                res.append(node.val + ",");
                queue.add(node.left);
                queue.add(node.right);
            }
            else {
                res.append("null,");
            }
        }
        res.deleteCharAt(res.length() - 1);
        res.append("]");
        return res.toString();
    }

    private SimpleTreeNode deserialize(String data) {
        if(data.equals("[]")) {
            return null;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        final SimpleTreeNode root = new SimpleTreeNode(Integer.parseInt(vals[0]));
        Queue<SimpleTreeNode> queue = new LinkedList<SimpleTreeNode>() {{ add(root); }};
        int i = 1;
        while(!queue.isEmpty()) {
            SimpleTreeNode node = queue.poll();
            if(!vals[i].equals("null")) {
                node.left = new SimpleTreeNode(Integer.parseInt(vals[i]));
                queue.add(node.left);
            }
            i++;
            if(!vals[i].equals("null")) {
                node.right = new SimpleTreeNode(Integer.parseInt(vals[i]));
                queue.add(node.right);
            }
            i++;
        }
        return root;
    }
}
